package geekTime.chapter18StampedLock;

import java.util.concurrent.locks.StampedLock;

/**
 * 锁的升级和降级
 * Created by LinGer on 2019/7/1
 */
public class LevelUpAndDown {

    private double x, y;
    private final StampedLock sl = new StampedLock();

    /**
     * 锁的升级和降级要慎重使用
     * 存在问题的方法
     * @param newX
     * @param newY
     */
    public void moveIfAtOrigin(double newX, double newY){
        long stamp = sl.readLock();
        try {
            while (x == 0.0 && y == 0.0) {
                long ws = sl.tryConvertToWriteLock(stamp);
                if(ws != 0L){
                    //锁升级成功，一定要把当前的stamp重新赋值
                    stamp = ws;
                    x = newX;
                    y = newY;
                    break;
                }else {
                    //锁升级失败，则释放当前读取锁，获取写锁
                    sl.unlockRead(stamp);
                    stamp = sl.writeLock();
                }
            }
        }finally {
            sl.unlock(stamp);
        }
    }
}
